<?php

declare(strict_types=1);

namespace app\controller;

use app\BaseController;
use think\exception\ValidateException;
use app\ErrorResult;
use app\model\Options;
use think\console\input\Option;

class Members extends BaseController
{
    protected $version = 'v1';

    /**
     * Api接口方法列表
     */
    public function index()
    {
    }

    /**
     * 会员注册
     */
    public function register()
    {
        $data = $this->request->post(['nickname', 'email', 'password']);

        try {
            $this->validate($data, 'app\validate\Members.register');
        } catch (ValidateException $th) {
            return $this->result(lang($th->getError()), [], ErrorResult::Msg2Code($th->getError()));
        }

        $insertData = $data;
        $insertData['uuid'] = uuid($data['email']);
        $insertData['avatar'] = generateAvatar($insertData['uuid']);
        $insertData['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        $insertData['create_ip'] = $this->request->ip();
        $insertData['update_ip'] = $this->request->ip();

        // 是否开启新用户审核
        if (Options::getValue('user_examine') === 1) {
            $insertData['status'] = 0;
        } else {
            $insertData['status'] = 1;
        }

        \app\model\Members::create($insertData);

        return $this->result(lang('success'));
    }

    /**
     * 会员登录
     */
    public function login()
    {
        $user = $this->request->post('user');
        $pwd = $this->request->post('password');

        if (empty($user) || empty($pwd)) {
            return $this->result(lang('User name or password cannot be empty'), 2000);
        }

        $member = \app\model\Members::where('email', $user)->find();
        if (empty($member)) {
            return ErrorResult::ErrorResult(2001);
        }

        if (password_verify($pwd, $member->password)) {
            // 更新用户信息
            $member->refreshLast();
            $token = \app\JsonWebToken::createJWT('system', 'created from login', 0, ['uuid' => $member->uuid]);

            return $this->result(lang('login successfully'), ['token' => $token]);
        } else {
            return ErrorResult::ErrorResult(2002);
        }
    }
}
